#include <ConfigFileReader.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <fstream>

ConfigFileReader::ConfigFileReader(const std::string filename)
{
    loadFile(filename);
}

ConfigFileReader::~ConfigFileReader()
{

}

bool ConfigFileReader::getConfigValue(const std::string key,std::string& value)
{
    value.clear();

    if(!m_loadOK)
    {
        return false;
    }

    std::map<std::string,std::string>::const_iterator it = m_configMap.find(key);
    if( it != m_configMap.end())
    {
        value = it->second;
        return true;
    }
    else
    {
        return false;
    }
    
}

bool   ConfigFileReader::setConfigValue(const std::string key,const std::string value)
{
    if(!m_loadOK)
    {
        return false;
    }

    std::map<std::string,std::string>::iterator it = m_configMap.find(key);
    if(it != m_configMap.end())
    {
        it->second = value;
    }
    else
    {
        m_configMap.insert(std::make_pair(key,value));
    }

    
    return writeFile(m_configFile);
}


bool  ConfigFileReader::loadFile(const std::string filename)
{
    m_configFile = filename;

    std::ifstream infile;
    infile.open(filename,std::ios::in);
    if(infile.fail())
    {
        return false;
    }

    std::string strLine;

    while(!infile.eof())
    {
        getline(infile,strLine);

        if(strLine.find("#") != std::string::npos || strLine.empty())
        {
            continue;
        }
        else
        {
            if(!parseLine(strLine))
            {
                return false;
            }
        }
        
    }

    infile.close();

    return true;
}

bool   ConfigFileReader::writeFile(const std::string filename)
{
    std::ofstream outfile;
    outfile.open(filename,std::ios::out | std::ios::trunc);
    if(outfile.fail())
    {
        return false;
    }

    char buff[256];
    std::map<std::string,std::string>::iterator it = m_configMap.begin();
    for (;it!=m_configMap.end();it++)
    {
        memset(buff,0,sizeof(buff));
        snprintf(buff,sizeof(buff),"%s=%s\n",it->first.c_str(),it->second.c_str());
        outfile.write(buff,strlen(buff));
    }
    

}

bool  ConfigFileReader::parseLine(std::string& strLine)
{
    int pos = strLine.find("=");
    if(pos != std::string::npos)
    {   
        std::string key = strLine.substr(0,pos);
        std::string value = strLine.substr(pos+1,strLine.length()-pos-1);
        m_configMap.insert(std::make_pair(key,value));
        return true;
    }
    else
    {
        return false;
    }
    

}

